package com.ljc;

import java.util.Arrays;

/**
 * @author clj
 * @date 2022/8/29
 * @desc
 * You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer.
 * The digits are ordered from most significant to least significant in left-to-right order.
 * The large integer does not contain any leading 0's.
 *
 * Increment the large integer by one and return the resulting array of digits.
 *
 * Example 1:
 * Input: digits = [1,2,3]
 * Output: [1,2,4]
 * Explanation: The array represents the integer 123.
 * Incrementing by one gives 123 + 1 = 124.
 * Thus, the result should be [1,2,4].
 *
 *  Example 2:
 * Input: digits = [4,3,2,1]
 * Output: [4,3,2,2]
 * Explanation: The array represents the integer 4321.
 * Incrementing by one gives 4321 + 1 = 4322.
 * Thus, the result should be [4,3,2,2].
 *
 * Example 3:
 * Input: digits = [9]
 * Output: [1,0]
 * Explanation: The array represents the integer 9.
 * Incrementing by one gives 9 + 1 = 10.
 * Thus, the result should be [1,0].
 */
public class E66PlusOne {
//    static int[] digits = new int[]{4,3,2,1};
    static int[] digits = new int[]{1,2,3};

    public static void main(String[] args) {
//        int[] r = plusOne(digits);
        int[] r = plusOne1(digits);
        System.out.println(Arrays.toString(r));

    }

    public static int[] plusOne(int[] digits) {
        int j = 1;
        for (int i = digits.length-1; i >=0 ; --i) {
            System.out.println("第j: " + j + "次循环");
            System.out.println("i: " + i);
            //既然继续在循环，那就说明进位还在，当前位还需+1
            digits[i] = digits[i] + 1;
            System.out.println("digits[i]: " + digits[i]);
            //如果当前位与10取余，不等于0，则表示该数不等于10，不需要进位，否则，需要进位1
            int b = digits[i]%=10;
            System.out.println("b: " + b);
            //说明此时进位已经成功消掉，没必要继续往前算了。
            if (digits[i]!=0) {
                int c = digits[i];
                System.out.println("c: " + c);
                System.out.println("d: " + Arrays.toString(digits));
                return digits;
            }
            j++;
        }
        //如果循环出来了，说明最后多出来一个进位1
        //要想出现这种情况，即进位1满到了最高位，，那这个数必然是100………这种情况
        //即进位一直向前进，一直消不掉
        digits=new int[digits.length+1];
        digits[0]=1;
        System.out.println("f: " + Arrays.toString(digits));
        //此时后面刚好都是0，即100………

        return digits;
    }

    public static int[] plusOne1(int[] digits) {
        for (int i = digits.length-1; i >=0 ; i--) {
            if (digits[i]+1==10){
                //如果该位数字+1等于10，则继续循环，表示需要进位1，否则，该位数字数字+1后，直接返回数组！
                digits[i]=0;
            }else {
                digits[i]=digits[i]+1;
                return digits;
            }
        }
        //若循环出，则表示仍需进位1，则数组长度+1，首位数字为1！
        int[] nums=new int[digits.length+1];
        nums[0]=1;
        return nums;
    }



}
